package org.jeecg.modules.daily.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.daily.entity.Daily;
import org.jeecg.modules.daily.entity.DailyZi;
import org.jeecg.modules.daily.service.IDailyService;
import org.jeecg.modules.daily.service.IDailyZiService;
import org.jeecg.modules.daily.vo.DailyAppVO;
import org.jeecg.modules.daily.vo.DailyPage;
import org.jeecg.modules.personalTask.entity.PersonalTask;
import org.jeecg.modules.personalTask.service.IPersonalTaskService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.TemplateMessageUtil;
import org.jeecg.modules.system.util.ThreadPoolManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 任务汇报
 * @Author: jeecg-boot
 * @Date:   2024-02-23
 * @Version: V1.0
 */
@Api(tags="任务汇报")
@RestController
@RequestMapping("/daily/daily")
@Slf4j
public class DailyController extends JeecgController<Daily, IDailyService> {
	@Autowired
	private IDailyService dailyService;
	@Autowired
	private IDailyZiService dailyZiService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ThreadPoolManager threadPoolManager;
	@Autowired
	private TemplateMessageUtil templateMessageUtil;
	@Autowired
	private IPersonalTaskService personalTaskService;

	/**
	 * 分页列表查询
	 *
	 * @param daily
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "任务汇报-分页列表查询")
	@ApiOperation(value="任务汇报-分页列表查询", notes="任务汇报-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Daily daily,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Daily> queryWrapper = QueryGenerator.initQueryWrapper(daily, req.getParameterMap());
		Page<Daily> page = new Page<Daily>(pageNo, pageSize);
		queryWrapper.orderByDesc("create_time");
		IPage<Daily> pageList = dailyService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@GetMapping("/getAppList")
	public Result<?> getAppList(){
		LambdaQueryWrapper<Daily> wrapper = Wrappers.lambdaQuery();
		wrapper.orderByDesc(Daily::getCreateTime);
		List<Daily> list = dailyService.list(wrapper);
		return Result.OK(list);
	}
	
	/**
	 *   添加
	 *
	 * @param dailyPage
	 * @return
	 */
	@AutoLog(value = "任务汇报-添加")
	@ApiOperation(value="任务汇报-添加", notes="任务汇报-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody DailyPage dailyPage) {
		Daily daily = new Daily();
		BeanUtils.copyProperties(dailyPage, daily);
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		daily.setName(user.getRealname());
		dailyService.saveMain(daily, dailyPage.getDailyZiList());
		threadPoolManager.executeTask(() -> sendTemplate(user.getRealname()));
		return Result.OK("添加成功！");
	}

	private void sendTemplate(String realname) {
		String stringDate = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
		List<SysUser> list = sysUserService.list();
		for (SysUser sysUser : list){
			String wxOpenid = sysUser.getWxOpenid();
			if (wxOpenid != null && !wxOpenid.isEmpty()){
				templateMessageUtil.getSendMessage(wxOpenid, "提交了任务汇报", realname, stringDate);
			}
		}
	}

	/**
	 *  编辑
	 *
	 * @param dailyPage
	 * @return
	 */
	@AutoLog(value = "任务汇报-编辑")
	@ApiOperation(value="任务汇报-编辑", notes="任务汇报-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody DailyPage dailyPage) {
		Daily daily = new Daily();
		BeanUtils.copyProperties(dailyPage, daily);
		Daily dailyEntity = dailyService.getById(daily.getId());
		if (dailyEntity == null) {
			return Result.error("未找到对应数据");
		}
		dailyService.updateMain(daily, dailyPage.getDailyZiList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务汇报-通过id删除")
	@ApiOperation(value="任务汇报-通过id删除", notes="任务汇报-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		dailyService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务汇报-批量删除")
	@ApiOperation(value="任务汇报-批量删除", notes="任务汇报-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.dailyService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务汇报-通过id查询")
	@ApiOperation(value="任务汇报-通过id查询", notes="任务汇报-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Daily daily = dailyService.getById(id);
		if(daily==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(daily);
	}

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "任务汇报子表通过主表ID查询")
	 @ApiOperation(value="任务汇报子表通过主表ID查询", notes="任务汇报子表-通主表ID查询")
	 @GetMapping(value = "/queryDailyZiByMainId")
	 public Result<?> queryDailyZiByMainId(@RequestParam(name="id",required=true) String id) {
		 LambdaQueryWrapper<DailyZi> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(DailyZi::getDailyId, id);
		 List<DailyZi> list = dailyZiService.list(wrapper);
		 return Result.OK(list);
	 }

	 @GetMapping("/queryDetailByIdForApp")
	 public Result<?> queryDetailByIdForApp(@RequestParam(name="id",required=true) String id){
		 Daily daily = dailyService.getById(id);
		 if(daily==null) {
			 return Result.error("未找到对应数据");
		 }
		 LambdaQueryWrapper<DailyZi> wrapper = Wrappers.lambdaQuery();
		 wrapper.eq(DailyZi::getDailyId, id);
		 List<Map<String, Object>> list = dailyZiService.listMaps(wrapper);
		 if (list == null || list.isEmpty()){
			 DailyAppVO dailyAppVO = new DailyAppVO();
			 BeanUtils.copyProperties(daily, dailyAppVO);
			 dailyAppVO.setDailyZiList(list);
			 return Result.OK(dailyAppVO);
		 }
		 List<String> taskIds = new ArrayList<>();
		 for (Map<String, Object> map: list){
			 String taskId = (String) map.get("task_id");
			 taskIds.add(taskId);
		 }
		 LambdaQueryWrapper<PersonalTask> taskWrapper = Wrappers.lambdaQuery();
		 taskWrapper.in(PersonalTask::getId, taskIds);
		 List<PersonalTask> taskList = personalTaskService.list(taskWrapper);
		 Map<String, String> textMap = new HashMap<>();
		 for (PersonalTask task : taskList){
			 String taskId = task.getId();
			 String text = task.getText();
			 textMap.put(taskId, text);
		 }
		 for (Map<String, Object> map: list){
			 String taskId = (String) map.get("task_id");
			 if (textMap.containsKey(taskId)){
				 map.put("task_text", textMap.get(taskId));
			 }
		 }
		 DailyAppVO dailyAppVO = new DailyAppVO();
		 BeanUtils.copyProperties(daily, dailyAppVO);
		 dailyAppVO.setDailyZiList(list);
		 return Result.OK(dailyAppVO);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param daily
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Daily daily) {
        return super.exportXls(request, daily, Daily.class, "任务汇报");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Daily.class);
    }

}
